package com.bai.localshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bai.localshop.context.BaseContext;
import com.bai.localshop.exception.BaseException;
import com.bai.localshop.mapper.AddressBookMapper;
import com.bai.localshop.pojo.dto.*;
import com.bai.localshop.pojo.vo.OrderSubmitVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bai.localshop.mapper.OrderItemMapper;
import com.bai.localshop.mapper.OrderMapper;
import com.bai.localshop.mapper.ProductMapper;
import com.bai.localshop.pojo.entity.Order;
import com.bai.localshop.pojo.entity.OrderItem;
import com.bai.localshop.pojo.entity.Product;
import com.bai.localshop.pojo.vo.OrderItemVO;
import com.bai.localshop.pojo.vo.OrderVO;
import com.bai.localshop.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import static com.bai.localshop.constant.SystemConstants.*;

/**
 * 订单服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ProductMapper productMapper;
    private final AddressBookMapper addressBookMapper;


    @Override
    public Page<OrderVO> pageQuery(OrderQueryDTO query) {
        Page<Order> page = new Page<>(query.getPage(), query.getPageSize());

        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(query.getOrderNumber() != null, Order::getOrderNumber, query.getOrderNumber())
                .eq(query.getUserId() != null, Order::getUserId, query.getUserId())
                .eq(query.getStatus() != null, Order::getStatus, query.getStatus())
                .orderByDesc(Order::getCreateTime);

        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);

        // 转换为VO
        Page<OrderVO> voPage = new Page<>();

        BeanUtil.copyProperties(orderPage, voPage);
        List<OrderVO> orderVOs = BeanUtil.copyToList(orderPage.getRecords(), OrderVO.class);

        // 设置订单项
        for (OrderVO orderVO : orderVOs) {
            List<OrderItem> orderItems = orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>()
                            .eq(OrderItem::getOrderId, orderVO.getId())
            );
            orderVO.setOrderItems(BeanUtil.copyToList(orderItems, OrderItemVO.class));
        }

        voPage.setRecords(orderVOs);
        return voPage;
    }

    @Override
    public OrderVO getById(Long id) {
        Order order = orderMapper.selectById(id);
        OrderVO orderVO = BeanUtil.copyProperties(order, OrderVO.class);

        // 设置订单项
        List<OrderItem> orderItems = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, id)
        );
        orderVO.setOrderItems(BeanUtil.copyToList(orderItems, OrderItemVO.class));

        return orderVO;
    }

    @Override
    @Transactional
    public void create(OrderCreateDTO orderCreateDTO) {
        // 生成订单号
        String orderNumber = "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6);

        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItemCreateDTO itemDTO : orderCreateDTO.getOrderItems()) {
            Product product = productMapper.selectById(itemDTO.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在");
            }
            BigDecimal subtotal = product.getPrice().multiply(BigDecimal.valueOf(itemDTO.getQuantity()));
            totalAmount = totalAmount.add(subtotal);
        }

        // 创建订单
//        Order order = new Order();
//        order.setOrderNumber(orderNumber);
//        order.setUserId(1L); // 这里应该从当前登录用户获取
//        order.setUsername("test_user"); // 这里应该从当前登录用户获取
//        order.setTotalAmount(totalAmount);
//        order.setStatus(0); // 待付款
//        order.setReceiverName(orderCreateDTO.getReceiverName());
//        order.setReceiverPhone(orderCreateDTO.getReceiverPhone());
//        order.setReceiverAddress(orderCreateDTO.getReceiverAddress());
//        order.setRemark(orderCreateDTO.getRemark());
//        orderMapper.insert(order);

        // 创建订单项
        for (OrderItemCreateDTO itemDTO : orderCreateDTO.getOrderItems()) {
            Product product = productMapper.selectById(itemDTO.getProductId());
//
//            OrderItem orderItem = new OrderItem();
//            orderItem.setOrderId(order.getId());
//            orderItem.setProductId(itemDTO.getProductId());
//            orderItem.setProductName(product.getName());
//            orderItem.setProductImage(product.getImage());
//            orderItem.setPrice(product.getPrice());
//            orderItem.setQuantity(itemDTO.getQuantity());
//            orderItem.setSubtotal(product.getPrice().multiply(BigDecimal.valueOf(itemDTO.getQuantity())));
//            orderItemMapper.insert(orderItem);
        }
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Order order = new Order();
        order.setId(id);
        order.setStatus(status);

        // 根据状态设置相应时间
        if (status == 1) { // 已付款
            order.setPayTime(LocalDateTime.now());
        } else if (status == 2) { // 已发货
            order.setShipTime(LocalDateTime.now());
        } else if (status == 3) { // 已完成
            order.setCompleteTime(LocalDateTime.now());
        }

        orderMapper.updateById(order);
    }

    @Override
    public void cancel(Long id) {
        updateStatus(id, 4); // 已取消
    }

    /**
     * 用户下单
     */
    @Override
    public OrderSubmitVO submit(OrderSubmitDTO requestParam) {
        //判断地址簿
        if (addressBookMapper.selectById(requestParam.getAddressBookId()) == null) {
            throw new BaseException("地址信息为空，请添加地址信息");
        }
        Long userId = BaseContext.getCurrentId();
        //向订单表插入数据
        Order order = Order.builder()
                .orderNumber(String.valueOf(System.currentTimeMillis()))
                .status(ORDER_PENDING_PAYMENT)
                .payStatus(PAY_STATUS_UNPAID)
                .userId(userId)
                .createTime(LocalDateTime.now())
                .build();
        BeanUtil.copyProperties(requestParam, order);
        //TODO 计算预计送达时间：拿到接单时间 根据地址判断，省内三天省外五天 接单之后才返回给用户预计到达时间
        //根据地址簿id查询省

//        String provinceName = addressBookMapper.selectById(requestParam.getAddressBookId()).getProvinceName();
//        if (!"四川".equals(provinceName)){
//            //设置送达时间为接单时间往后延五天
//
//        }else{
//            //设置送达时间为接单时间往后延三天
//        }
        int insert = orderMapper.insert(order);
        if (insert < 0) {
            throw new BaseException("订单创建失败");
        }
        return BeanUtil.toBean(order, OrderSubmitVO.class);
    }

    /**
     * 订单支付
     */
    @Override
    public void payment(OrdersPaymentDTO requestParam) {
        //满足 支付状态为未支付，订单状态为待支付，修改支付状态，
        Order orderDB = orderMapper.selectById(requestParam.getId());
        if (orderDB == null) {
            throw new BaseException("订单不存在");
        }
        if (!ORDER_PENDING_PAYMENT.equals(orderDB.getStatus()) && PAY_STATUS_UNPAID.equals(orderDB.getPayStatus())) {
            throw new BaseException("订单状态异常");
        }
        LambdaUpdateWrapper<Order> updateWrapper = Wrappers.lambdaUpdate(Order.class)
                .set(Order::getStatus, ORDER_TO_BE_CONFIRMED)
                .set(Order::getPayStatus, PAY_STATUS_PAID)
                .set(Order::getPayMethod, requestParam.getPayMethod())
                .set(Order::getPayTime, LocalDateTime.now())
                .eq(Order::getId, requestParam.getId());
        orderMapper.update(updateWrapper);
    }
}


